package com.zjm.creational.singleton.type05;

/**
 * 懒汉式（线程安全、同步代码块）
 */
public class SingletonTest05 {
    public static void main(String[] args) {
        // 模拟10个线程并发获取单例对象
        for (int i = 1; i <= 10; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + " 获取到的实例：" + Singleton.getInstance());
            }, "线程-" + i).start();
        }
    }
}

class Singleton {
    private static Singleton INSTANCE;

    // 构造器私有化
    private Singleton() {
    }

    // 提供公共的静态方法，返回实例对象,同步代码块解决线程安全
    public static Singleton getInstance() {
        if (INSTANCE == null) {
            synchronized (Singleton.class) {
                INSTANCE = new Singleton();
            }
        }
        return INSTANCE;
    }
}
